package com.u8.sdk.plugin;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import com.u8.sdk.IPay;
import com.u8.sdk.PayParams;
import com.u8.sdk.PluginFactory;
import com.u8.sdk.U8SDK;
import com.u8.sdk.utils.U8HttpUtils;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;

/***
 * 支付插件
 * @author xiaohei
 *
 */
public class U8Pay{
	
	private static U8Pay instance;
	
	private ProgressDialog loadingActivity = null;
	
	private IPay payPlugin;
	
	private HandlerThread handlerThread = new HandlerThread("payThread");  
	private Handler payHandler;
	private PayParams payParams;
	private U8Pay(){
		
	}
	
	public static U8Pay getInstance(){
		if(instance == null){
			instance = new U8Pay();
		}
		return instance;
	}
	
	public void init(){
		handlerThread.start();
		payHandler = new Handler(handlerThread.getLooper()) {  
			@Override  
            public void handleMessage(Message msg) { 
            	//支付
            	String result = msg.getData().getString("result");
            	Log.i("U8SDK creat order", result);
            	if(result != null && result!= ""){
            		payParams.setOrderKey(result);
                	payPlugin.pay(payParams);
                	payParams = null;
                	hideProgressDialog();
            	}
            }
        };
		this.payPlugin = (IPay)PluginFactory.getInstance().initPlugin(IPay.PLUGIN_TYPE);
	}
	
	
	//创建唯一标识符号
	@SuppressLint("SimpleDateFormat")
	private String getcode() {
        SimpleDateFormat slp = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String st = slp.format(new Date(System.currentTimeMillis())) + new Random().nextInt(100000) ;
        return st;
    }
	
	/***
	 * 支付接口（弹出支付界面）
	 * @param data
	 */
	public void pay(PayParams data){
		if(this.payPlugin == null){
			return;
		}
		if(payParams != null){
			return;
		}
		Log.i("per pay", "getExtension :" + data.getExtension());
		
		payParams = data;
		String orderKey = getcode();
		payParams.setOrderKey(orderKey);
		showProgressDialog("订单创建中..");
		//服务器记录支付
		payHandler.post(new Runnable() {  
            @Override  
            public void run() {  
            	String url = "http://auth.sdk.m.51wan.com:8080/Sdk_PrePay.php";
            	Map<String, String> tradeData = new HashMap<String, String>();
            	tradeData.put("chanel", U8SDK.getInstance().getCurrChannelName());
            	tradeData.put("appID", U8SDK.getInstance().getAppID());
            	
            	tradeData.put("cpOrderID", payParams.getOrderID());
            	tradeData.put("itemId", payParams.getProductId());
            	tradeData.put("itemName", payParams.getProductName());
            	tradeData.put("itemDesc", payParams.getProductDesc());
            	tradeData.put("price", ""+payParams.getPrice());
            	tradeData.put("buyNum", ""+payParams.getBuyNum());
            	tradeData.put("coinNum", ""+payParams.getCoinNum());
            	tradeData.put("serverId", payParams.getServerId());
            	tradeData.put("serverName", payParams.getServerName());
            	tradeData.put("roleId", payParams.getRoleId());
            	tradeData.put("roleName", payParams.getRoleName());
            	tradeData.put("roleLevel", ""+payParams.getRoleLevel());
            	tradeData.put("vip", payParams.getVip());
            	tradeData.put("extension", payParams.getExtension());
            	String result = U8HttpUtils.httpPost(url,tradeData);
    			
            	Message msg = new Message();   
            	Bundle data = new Bundle();  
                data.putString("result", result);  
                msg.setData(data);  
                payHandler.sendMessage(msg);
            }  
        });
	}
	
	private void showProgressDialog(String msg){
		if(loadingActivity != null){
			return;
		}
		
        loadingActivity = new ProgressDialog(U8SDK.getInstance().getContext());
        loadingActivity.setIndeterminate(true);
        loadingActivity.setCancelable(false);
        loadingActivity.setMessage(msg);
        loadingActivity.setOnCancelListener(new DialogInterface.OnCancelListener() {
			@Override
			public void onCancel(DialogInterface arg0) {

			}
		});		
        loadingActivity.show();
	}
	
	private void hideProgressDialog(){
		if(loadingActivity == null){
			return;
		}
		loadingActivity.dismiss();
		loadingActivity = null;
	}
}
